package cn.tedu.smartos.family_user.service.impl;

import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.family_user.mapper.ElectronicFenceMapper;
import cn.tedu.smartos.family_user.mapper.LocationRecordMapper;
import cn.tedu.smartos.family_user.mapper.PositionAlertMapper;
import cn.tedu.smartos.family_user.pojo.entity.ElectronicFence;
import cn.tedu.smartos.family_user.pojo.entity.LocationRecord;
import cn.tedu.smartos.family_user.pojo.entity.PositionAlertRecord;
import cn.tedu.smartos.family_user.pojo.vo.PositionAlertVO;
import cn.tedu.smartos.family_user.service.PositionAlertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PositionAlertServiceImpl implements PositionAlertService {
    @Autowired
    private PositionAlertMapper alertMapper;

    @Autowired
    private LocationRecordMapper locationRecordMapper;

    @Autowired
    private ElectronicFenceMapper fenceMapper;

    @Transactional
    @Override
    public void createBoundaryAlert(Long elderlyUserId, Long familyUserId, Long fenceId,
                                    Long recordId, String alertContent) {
        PositionAlertRecord alert = new PositionAlertRecord();
        alert.setElderlyUserId(elderlyUserId);
        alert.setFamilyUserId(familyUserId);
        alert.setFenceId(fenceId);
        alert.setRecordId(recordId);
        alert.setAlertContent(alertContent);
        alert.setAlertTime(new Date());
        alert.setHandleStatus(0); // 未处理

        alertMapper.insertAlert(alert);
        log.info("创建位置越界预警: 老人ID={}, 围栏ID={}, 预警内容={}", elderlyUserId, fenceId, alertContent);
    }

    @Override
    public List<PositionAlertVO> getAlertsByElderly(Long elderlyUserId, Integer limit) {
        if (limit == null || limit <= 0) limit = 10;

        List<PositionAlertRecord> alerts = alertMapper.selectAlertsByElderly(elderlyUserId, limit);

        return alerts.stream().map(alert -> {
            PositionAlertVO vo = new PositionAlertVO();
            BeanUtils.copyProperties(alert, vo);

            // 获取位置记录信息
            LocationRecord location = locationRecordMapper.selectLocationRecordById(alert.getRecordId());
            if (location != null) {
                vo.setLatitude(location.getLatitude());
                vo.setLongitude(location.getLongitude());
                vo.setAddress(location.getAddress());
            }

            // 获取围栏名称
            ElectronicFence fence = fenceMapper.selectFenceById(alert.getFenceId());
            if (fence != null) {
                vo.setFenceName(fence.getFenceName());
            }

            // 设置处理状态文本
            switch (alert.getHandleStatus()) {
                case 0: vo.setHandleStatusText("未处理"); break;
                case 1: vo.setHandleStatusText("已处理"); break;
                default: vo.setHandleStatusText("未知状态");
            }

            return vo;
        }).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void handleAlert(Long alertId) {
        PositionAlertRecord alert = alertMapper.selectAlertById(alertId);
        if (alert == null) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "预警记录不存在");
        }

        if (alert.getHandleStatus() == 1) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "预警已处理");
        }

        alert.setHandleStatus(1);
        alert.setHandleTime(new Date());
        alertMapper.updateAlert(alert);
        log.info("处理位置预警: ID={}", alertId);
    }
}